package com.cat.slidingWindow;

/**
 * @author cat
 * @description https://leetcode.cn/problems/continuous-subarrays/
 * @create 2025/7/31 20:41
 * @since JDK17
 */

public class Solution22 {
    static int N = ((int) (1e5 + 10)), maxh, maxt, minh, mint;
    static int[] maxDeque = new int[N], minDeque = new int[N], nums;

    void push(int x) {
        // 放入 大->小的单调队列
        while (maxh < maxt && nums[maxDeque[maxt - 1]] <= nums[x]) {    //
            maxt--;
        }
        maxDeque[maxt++] = x;
        // 放入 小->大的单调队列
        while (minh < mint && nums[minDeque[mint - 1]] >= nums[x]) {
            mint--;
        }
        minDeque[mint++] = x;
    }

    void pop(int l) {
        if (l == maxDeque[maxh]) maxh++;
        if (l == minDeque[minh]) minh++;
    }

    boolean judge() {
        return nums[maxDeque[maxh]] - nums[minDeque[minh]] <= 2;
    }

    public long continuousSubarrays(int[] arr) {
        long ans = 0;
        maxh = maxt = minh = mint = 0;
        nums = arr;
        int n = nums.length;
        for (int l = 0, r = 0; r < n; r++) {
            push(r);    // 将r这个数字放入
            while (!judge()) {
                pop(l++);
            }
            ans += r - l + 1;
        }
        return ans;
    }
}
